package com.school.service;

import com.school.common.PageRequest;
import com.school.common.PageResult;
import com.school.common.ResultCode;
import com.school.dao.BuildingDao;
import com.school.entity.Building;
import com.school.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 楼栋服务类
 */
@Slf4j
@Service
public class BuildingService {
    
    @Autowired
    private BuildingDao buildingDao;
    
    /**
     * 添加楼栋
     */
    @Transactional(rollbackFor = Exception.class)
    public Long add(Building building) {
        // 验证楼栋名称是否已存在
        Building existBuilding = buildingDao.findByBuildingName(building.getBuildingName());
        if (existBuilding != null) {
            throw new BusinessException(ResultCode.BUILDING_NAME_EXISTED);
        }
        
        // 验证已入住人数不能超过容纳人数
        if (building.getOccupied() > building.getCapacity()) {
            throw new BusinessException("已入住人数不能超过容纳人数");
        }
        
        return buildingDao.insert(building);
    }
    
    /**
     * 更新楼栋
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(Building building) {
        Building existBuilding = buildingDao.findById(building.getId());
        if (existBuilding == null) {
            throw new BusinessException(ResultCode.BUILDING_NOT_EXIST);
        }
        
        // 验证已入住人数不能超过容纳人数
        if (building.getOccupied() > building.getCapacity()) {
            throw new BusinessException("已入住人数不能超过容纳人数");
        }
        
        buildingDao.update(building);
    }
    
    /**
     * 删除楼栋
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        Building existBuilding = buildingDao.findById(id);
        if (existBuilding == null) {
            throw new BusinessException(ResultCode.BUILDING_NOT_EXIST);
        }
        
        buildingDao.deleteById(id);
    }
    
    /**
     * 批量删除楼栋
     */
    @Transactional(rollbackFor = Exception.class)
    public int batchDelete(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new BusinessException("删除ID列表不能为空");
        }
        
        log.info("批量删除楼栋，数量: {}", ids.size());
        return buildingDao.batchDelete(ids);
    }
    
    /**
     * 根据ID查询楼栋
     */
    public Building getById(Long id) {
        Building building = buildingDao.findById(id);
        if (building == null) {
            throw new BusinessException(ResultCode.BUILDING_NOT_EXIST);
        }
        return building;
    }
    
    /**
     * 查询所有楼栋
     */
    public List<Building> getAllBuildings() {
        return buildingDao.findAll();
    }
    
    /**
     * 分页查询楼栋列表
     */
    public PageResult<Building> getPageList(String buildingName, PageRequest pageRequest) {
        Map<String, Object> params = new HashMap<>();
        params.put("buildingName", buildingName);
        params.put("offset", pageRequest.getOffset());
        params.put("limit", pageRequest.getLimit());
        
        List<Building> list = buildingDao.findByPage(params);
        long total = buildingDao.count(params);
        
        return PageResult.of(pageRequest.getPageNum(), pageRequest.getPageSize(), total, list);
    }
    
    /**
     * 获取楼栋统计信息
     */
    public Map<String, Object> getStatistics() {
        List<Building> buildings = buildingDao.findAll();
        
        int totalBuildings = buildings.size();
        int totalRooms = 0;
        int totalCapacity = 0;
        int totalOccupied = 0;
        
        for (Building building : buildings) {
            totalRooms += building.getTotalRooms();
            totalCapacity += building.getCapacity();
            totalOccupied += building.getOccupied();
        }
        
        double avgOccupancyRate = totalCapacity > 0 ? 
                Math.round((double) totalOccupied / totalCapacity * 10000.0) / 100.0 : 0.0;
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("totalBuildings", totalBuildings);
        statistics.put("totalRooms", totalRooms);
        statistics.put("totalCapacity", totalCapacity);
        statistics.put("totalOccupied", totalOccupied);
        statistics.put("avgOccupancyRate", avgOccupancyRate);
        
        return statistics;
    }
}


